﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using seejee_Backendium.Core.Interfaces;
using seejee_Backendium.Core.Models;
using seejee_Backendium.Data.Services;

namespace seejee_Backendium.WEB.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class userAppController : Controller
    {
        private readonly ILogger<userAppController> _logger;
        private readonly IUserAPPsService _userAPPsService;
        public userAppController(ILogger<userAppController> logger,IUserAPPsService userAPPsService){
            _logger = logger;
            _userAPPsService = userAPPsService;
        }
        [HttpGet]
        public async Task<IActionResult> GetAllUserApp(
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 10,
            [FromQuery] string sortBy = "name",
            [FromQuery] string sortDirection = "asc")
        {
            try
            {
                _logger.LogInformation("获取用户APP列表，参数：page={Page}, pageSize={PageSize}, sortBy={SortBy}, sortDirection={SortDirection}",
                    page, pageSize, sortBy, sortDirection);

                // 获取总记录数
                var totalCount = await _userAPPsService.GetCountAsync();

                // 获取分页数据
                var Userapps = await _userAPPsService.GetAllAsync(page, pageSize, sortBy, sortDirection);

                _logger.LogInformation("获取到 {Count} 条用户记录", Userapps?.Count());

                return Ok(new
                {
                    Success = true,
                    Data = new
                    {
                        Items = Userapps,
                        Total = totalCount,
                        Page = page,
                        PageSize = pageSize
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户APP列表时发生错误");
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "服务器内部错误",
                    Error = ex.Message
                });
            }
        }
        [HttpPost("{add}")]
        public async Task<IActionResult> AddUserApp([FromBody] UserApp userApp)
        {
            try
            {
                _logger.LogInformation("添加新用户：{@UserApp}", userApp);

                // 基本验证
                if (string.IsNullOrWhiteSpace(userApp.userName))
                {
                    return BadRequest(new { success = false, message = "用户姓名不能为空" });
                }

                var addedUserApp = await _userAPPsService.AddAsync(userApp);

                return Ok(new
                {
                    Success = true,
                    Data = userApp
                });
            }
            catch (DbUpdateException ex)
            {
                _logger.LogError(ex, "添加用户APP时数据库错误");
                return StatusCode(500, new
                {
                    success = false,
                    message = "添加用户失败，可能已存在用户学生",
                    error = ex.InnerException?.Message
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加用户  时发生错误");
                return StatusCode(500, new
                {
                    success = false,
                    message = "服务器内部错误",
                    error = ex.Message
                });
            }
        }
        [HttpDelete("{name}")]
        public async Task<IActionResult> DeleteUserByName(string name)
        {
            try
            {
                _logger.LogInformation("尝试删除用户: {Name}", name);

                var user = await _userAPPsService.GetByIdAsync(name);
                if (user == null)
                {
                    _logger.LogWarning("未找到用户: {Name}", name);
                    return NotFound(new
                    {
                        success = false,
                        message = $"用户 {name} 不存在"
                    });
                }

                int affectedRows = await _userAPPsService.DelectByNameAsync(name);
                if (affectedRows > 0)
                {
                    _logger.LogInformation("成功删除用户: {Name}", name);
                    return NoContent(); // 204 No Content
                }

                _logger.LogWarning("删除用户未生效: {Name}", name);
                return BadRequest(new
                {
                    success = false,
                    message = "删除操作未生效"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除用户 {Name} 时发生错误", name);
                return StatusCode(500, new
                {
                    success = false,
                    message = "服务器内部错误",
                    error = ex.Message
                });
            }
        }
    }
}
